package com.dycong.common.network;

import com.dycong.common.common.StringUtil;

import lombok.Getter;
import lombok.Setter;
import org.codehaus.plexus.util.IOUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yu on 15-5-25.
 */
public class InteractHttpClient extends HttpStatusClient {

    public InteractHttpClient() {
    }

    public InteractHttpClient(String appKey, String appCode) {
        this.appKey = appKey;
        this.appCode = appCode;
    }

    @Getter
    @Setter
    private String appKey;

    @Getter
    @Setter
    private String appCode;

    private void prepare(String content) {
        if (headerMap == null)
            headerMap = new HashMap<>();
        String timestamp = System.currentTimeMillis() + "";
        headerMap.put("appKey", appKey);
        headerMap.put("timestamp", timestamp);
        String forMd5 = content + timestamp + appCode;
        logger.debug("for MD5: " + forMd5);
        headerMap.put("signature", StringUtil.getMd5HexByUtf8Encoding(forMd5));
    }

    @Override
    public String doGet(String url, String encoding) throws IOException {
        prepare("");
        return super.doGet(url, encoding);
    }


    @Override
    public String doPost(String url, String encoding) throws IOException {
        String content = IOUtil.toString(mapToRequestEntity(paramMap, encoding).getContent(), encoding);
        prepare(content);
        return super.doPost(url, encoding);
    }


    @Override
    public String postJson(String url, String encoding, Map<String, String> header, String json) throws IOException {
        prepare(json);
        return super.postJson(url, encoding, header, json);
    }
}
